package com.edu.dao.impl;

import com.edu.dao.BaseDao;
import com.edu.dao.UserDao;
import com.edu.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author:max
 * @Date: 2024/9/14 16:12
 * @Description:
 */


public class UserDaoImpl implements UserDao {
    @Override
    public int insert(User user) {
        int row=0;
        Connection con = null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String sql="INSERT INTO user(userName,userPW,reallyName) VALUES(?,?,?)";
        System.out.println(sql);
        try {
            con= BaseDao.getConn();
            ps=con.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getUserPW());
            ps.setString(3, user.getReallyName());
            row= ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeAll(con,ps, null);
        }
        return row;
    }

    @Override
    public User select(String userNum, String userPW) {
        Connection con = null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        User user=null;
        String sql = "SELECT * FROM user WHERE userName =? AND userPW =?";
        try {
            con=BaseDao.getConn();
            ps=con.prepareStatement(sql);
            ps.setString(1, userNum);
            ps.setString(2, userPW);
            rs= ps.executeQuery();
            if (rs.next()){
                user = new User();
                user.setUserId(rs.getInt("userId"));
                user.setUserName(rs.getString("userName"));
                user.setUserPW(rs.getString("userPW"));
                user.setReallyName(rs.getString("reallyName"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeAll(con,ps,rs);
        }
        return user;
    }

    @Override
    public User selectByUsername(String userName) {
        Connection con = null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        User user=null;
        String sql = "SELECT * FROM user WHERE userName=?";
        try {
            con=BaseDao.getConn();
            ps=con.prepareStatement(sql);
            ps.setString(1, userName);
            rs= ps.executeQuery();
            System.out.println(sql);
            if (rs.next()){
                user = new User();
                System.out.println("1111111111111111111");
                user.setUserId(rs.getInt("userId"));
                user.setUserName(rs.getString("userName"));
                user.setUserPW(rs.getString("userPW"));
                user.setReallyName(rs.getString("reallyName"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeAll(con,ps,rs);
        }
        return user;
    }
}
